package com.baizhi.filter;

import com.baizhi.utils.JwtUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class CheckJwtFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //检查token
        String uri = exchange.getRequest().getURI().toString();
        //不需要拦截所有请求需要过滤一下，以user打头的都不需要验证token
        if (uri.indexOf("/user/")==-1) {//请求的用户微服务
            List<String> authorization = exchange.getRequest().getHeaders().get("Authorization");
            if(authorization!=null&&authorization.size()>0){
                String token = authorization.get(0);
                try {
                    JwtUtils.verify(token);
                } catch (Exception e) {
                    e.printStackTrace();
                    //拦截
                    exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
                    return exchange.getResponse().setComplete();

                }
            }else{
                //拦截
                exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
                return exchange.getResponse().setComplete();
            }
        }
        //放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
